const respJson = require('../../utils/respJson')
const cartModel = require('../../db/cart')
const writeErr = require('../../utils/writeErr')

module.exports = {
    //添加购物车
    async add(req, resp) {
        //获取post的数据
        let {
            userId,
            dishId,
            number,
            speandkind
        } = req.body
        if (!userId || !dishId || !number || !speandkind) {
            respJson(resp, 401, '数据不能为空！')
            return
        }
        //查找
        try {
            let docs = await cartModel.findOne({
                userId,
                dishId,
                speandkind
            })
            if (docs) {
                //读到数据了，增加数量
                docs.number += +number
                //修改数据库中的number
                try {
                    docs = await cartModel.updateOne({
                        userId,
                        dishId,
                        speandkind
                    }, {
                        $set: {
                            number: docs.number
                        }
                    })
                    respJson(resp, 200, '购物车添加成功！')
                } catch (err) {
                    writeErr(err)
                    respJson(resp, 507, '购物车添加失败！')
                }
                return
            }
            //没有读到数据,直接新增
            try {
                docs = await cartModel.insertMany({
                    userId,
                    dishId,
                    speandkind,
                    number
                })
                respJson(resp, 200, '购物车添加成功！')
            } catch (err) {
                writeErr(err)
                respJson(resp, 507, '购物车添加失败！')
            }
        } catch (err) {
            writeErr(err)
            respJson(resp, 507, '购物车添加失败！')
        }
    },

    //获取当前用户购物车数量
    async getnum(req, resp) {
        //接受当前用户id
        let {
            userId
        } = req.params

        try {
            let docs = await cartModel.count({
                userId
            })
            respJson(resp, 200, '购物车数量获取成功！', {
                number: docs
            })
        } catch (err) {
            writeErr(err)
            respJson(resp, 508, '购物车数量获取失败！')
        }
    },

    //获取购物车所有商品
    async getall(req, resp) {
        //接收用户id
        let {
            userId
        } = req.params
        try {
            let docs = await cartModel.find({
                userId
            })
            respJson(resp, 200, '购物车商品获取成功！', {
                carts: docs
            })
        } catch (err) {
            writeErr(err)
            respJson(resp, 509, '购物车商品获取失败！')
        }
    }
}